// pages/user/vip.js
var app = getApp();
var rootDocment = app.globalData.postUrl;
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

Page({

    /**
     * 页面的初始数据
     */
    data: {
        navHeight: app.globalData.barInfo.navHeight, //导航栏高度
        defaultAvatarUrl: defaultAvatarUrl,
        kefu: wx.getStorageSync('kefu') ? wx.getStorageSync('kefu') : '',
        showKefu: false,
        show: false,
        pay_type: 1,
        order_sn: null,
        vip_amount: '',
        //pay_total:0.01
        info: {
            product: {
                id: 222,
                pic: "https://lhs.tann.cc/upload/pic/goods/66bfff915a814.png",
                price: "398.00",
                title: "榴莲礼品卡【榴皇树】"
            }
        },
        goodsList: [{
                id: 1,
                imageUrl: '/images/goods1.jpg',
                title: '【热礼冷送】金枕榴莲包裹',
                gifts: '赠送：榴莲整果1个+两盒果肉+4只冰淇淋',
                price: '399',
                selected: true
            },
            // 更多商品数据...
        ],
        rootDocment: rootDocment,
        is_privacy: false,
        link_name: '',
        link_tel: '',
        link_addr: '',
        on_link_addr: '',
        OpenVipInfo: {},
        pay_show: false,
        address_id: 0,
        goods_list: [],
        goods_id: null,
        ck_index: 0,
        topOpacity: 0,
    },

    onPageScroll(e) {
        if (e.scrollTop > 50) {
            let opacity = e.scrollTop / 300;
            opacity = opacity > 1 ? 1 : opacity;
            this.setData({
                topOpacity: opacity
            });
        } else {
            this.setData({
                topOpacity: 0
            });
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.getOpenVipInfo()
    },
    set_ck_on(e) {
        let {
            item,
            index
        } = e.currentTarget.dataset
        console.log(e.currentTarget.dataset.item);
        console.log(e.currentTarget.dataset.index);
        this.setData({
            goods_id: item.id,
            ck_index: index,
        })
    },
    goDetail(e) {
        let {
            id
        } = e.currentTarget.dataset
        wx.navigateTo({
            url: `/pages/goods/card_goods_detail?id=${id}`,
        })
    },
    radioChange(e) {
        console.log(e);
        let is = this.data.is_privacy
        this.setData({
            is_privacy: !is
        })
    },
    onPayment() {
        var t = this
        var paraArr = new Array();
        paraArr['user_id'] = wx.getStorageSync('user_id3');
        // paraArr['address_id'] = t.data.address_id;
        // paraArr['goods_id'] = t.data.goods_id;

        var sign = app.signature(paraArr);
        wx.request({
            url: rootDocment + '/api/llgn/openVip',
            data: {
                user_id: paraArr['user_id'],
                // address_id: paraArr['address_id'],
                // goods_id: paraArr['goods_id'],
                // sign: sign
            },
            method: 'POST',
            header: {},
            success: function (res) {
                if (res.data.code == 1003) {
                    wx.showModal({
                        title: '提示',
                        content: res.data.msg || '绑定手机号才可购买',
                        success(res) {
                            if (res.confirm) {
                                wx.navigateTo({
                                    url: '/pages/shouji/shouji',
                                })
                            } else if (res.cancel) {
                                console.log('用户点击取消')
                            }

                        }
                    })
                    return
                }
                t.setData({
                    order_sn: res.data.data.order_sn
                }, () => {
                    wx.showModal({
                        title: `${t.data.vip_express_time ? '续费': '开通'}VIP`,
                        content: `立即支付${t.data.vip_amount}元`,
                        // showCancel: false,
                        success: (res) => {
                            console.log();
                            if (res.confirm) {
                                t.payNow()
                            }

                        }
                    })

                })
                // console.log(res.data.data.order_sn);
            }
        })
    },
    // 获取开通会员信息
    getOpenVipInfo() {
        // /api/llgn/getVipInfo
        var t = this
        var paraArr = new Array();

        var sign = app.signature(paraArr);
        wx.request({
            url: rootDocment + '/api/llgn/getVipInfo',
            data: {
                sign: sign
            },
            method: 'GET',
            header: {},
            success: function (res) {
                console.log('获取vip开通信息', res.data.data);

                t.setData({
                    OpenVipInfo: res.data.data,
                    goods_list: res.data.data.goods_list,
                    goods_id: res.data.data.goods_list[0].id
                })
            }
        })
    },
    //立即支付
    payNow: function () {
        var that = this;
        var paraArr = new Array();
        paraArr['order_sn'] = that.data.order_sn;
        var sign = app.signature(paraArr);
        if (that.data.pay_type == 1) { //微信支付

            // path: `/pages/pay/pay?storeId=${'M1747810615612809216'}&orderNo=${that.data.order_sn}&orderAmount=${that.data.vip_amount}&public=1`,
            wx.openEmbeddedMiniProgram({
                appId: 'wx3e64b506e01256fd',
                //M1747810615612809216
                path: `/pages/pay/pay?storeId=${'M1747810615612809216'}&orderNo=${that.data.order_sn}&orderAmount=${that.data.vip_amount}&public=1`,
                extraData: {
                    aa: '1111'
                },
                envVersion: 'release', //B的类型  trial体验版, ‘release’正式版    ‘develop’开发版
                success: function () {
                    app.globalData.isSuccess = '1'
                    app.globalData.pay_order_no = that.data.order_sn

                    console.log(app.globalData.isSuccess)
                    console.log('跳转小程序成功');
                    that.setData({
                        submit_btn_fal: false,
                        pay_show: false
                    })
                    wx.request({
                        url: rootDocment + '/api/Query',
                        data: {
                            order_sn: paraArr['order_sn'],
                            sign: sign
                        },
                        method: 'POST',
                        header: {},
                        success: function (res) {
                            console.log('res支付跳转订单查询', res)
                        }
                    })
                    wx.request({
                        url: rootDocment + '/api/query/cross',
                        data: {
                            order_sn: paraArr['order_sn'],
                            sign: sign
                        },
                        method: 'POST',
                        header: {},
                        success: function (res) {
                            console.log('res支付跳转订单轮询查询', res)
                        }
                    })
                },
                fail: function () {
                    console.log('跳转小程序失败');
                    that.setData({
                        submit_btn_fal: false
                    })
                }
            })
            return
            paraArr['order_sn'] = that.data.order_sn;
            paraArr['openid'] = that.data.userInfo.openID;
            paraArr['total'] = 40;
            paraArr['uid'] = that.data.userInfo.userID;
            paraArr['order_type'] = 1;
            var sign = app.signature(paraArr);
            wx.request({
                url: rootDocment + '/api/miniapp_pay/wxPay',
                data: {
                    order_sn: paraArr['order_sn'],
                    openid: paraArr['openid'],
                    total: paraArr['total'],
                    uid: paraArr['uid'],
                    order_type: paraArr['order_type'],
                    sign: sign
                },
                method: 'GET',
                header: {},
                success: function (res) {
                    console.log(res.data);
                    wx.requestPayment({
                        'timeStamp': res.data.timeStamp,
                        'nonceStr': res.data.nonceStr,
                        'package': res.data.package,
                        'signType': 'MD5',
                        'paySign': res.data.paySign,
                        'success': function (res) {
                            if (that.data.order_type == 1) {
                                wx.showModal({
                                    title: '提示',
                                    content: '开通成功',
                                    showCancel: false
                                })
                            } else {
                                app.gotaburl('user/index');
                            }
                        },
                        'fail': function (res) {
                            console.log(res);
                        }
                    })

                }
            })
        } else if (that.data.pay_type == 3) { //余额支付
            var paraArr1 = new Array();
            paraArr1['sn'] = that.data.order_sn;
            paraArr1['user_id'] = that.data.userInfo.userID;
            var sign = app.signature(paraArr1);
            wx.request({
                url: rootDocment + '/api/miniapp_pay/balancePay',
                data: {
                    sn: paraArr1['sn'],
                    user_id: paraArr1['user_id'],
                    sign: sign
                },
                method: 'POST',
                header: {},
                success: function (res) {
                    if (res.data.code == 1001) {
                        wx.showModal({
                            title: '提示',
                            content: '开通成功',
                            showCancel: false
                        })
                    } else {
                        wx.showModal({
                            title: '提示',
                            content: res.data.msg,
                            showCancel: false,

                        })
                    }
                    that.setData({
                        pay_show: false
                    })
                }
            })
        } else if (that.data.pay_type == 4) { //货到付款
            paraArr['sn'] = that.data.order_sn;
            paraArr['user_id'] = that.data.userInfo.userID;
            var sign = app.signature(paraArr);
            wx.request({
                url: rootDocment + '/api/miniapp_pay/codPay',
                data: {
                    sn: paraArr['sn'],
                    user_id: paraArr['user_id'],
                    sign: sign
                },
                method: 'POST',
                header: {},
                success: function (res) {
                    if (res.data.code == 1001) {
                        app.redirect('user/myorder', 'type=1');
                    } else {
                        wx.showModal({
                            title: '提示',
                            content: res.data.msg,
                            showCancel: false
                        })
                    }
                }
            })
        }
        setTimeout(() => {
            this.getUserInfo()
        }, 500)

    },

    onClose() {
        this.setData({
            show: false
        });
    },
    onPayClose() {
        this.setData({
            pay_show: false
        });
    },
    onPayOpen() {
        if (!this.data.is_privacy) {
            wx.showToast({
                title: '请同意会员协议',
                icon: 'none'
            })
            return
        }
        this.setData({
            pay_show: true
        });
    },

    //切换支付方式
    changePay: function (e) {
        var that = this;
        that.setData({
            pay_type: e.detail.value
        });
    },
    /**
     * 获取用户信息
     */
    getUserInfo: function () {
        var that = this;
        var paraArr = new Array();
        paraArr['id'] = wx.getStorageSync('user_id3')
        var sign = app.signature(paraArr);
        wx.request({
            url: rootDocment + '/api_user/' + paraArr['id'],
            data: {
                sign: sign
            },
            method: 'GET',
            header: {},
            success: function (res) {
                console.log(res.data, '1111111111');
                let text = res.data.data.vip_express_time
                if (text == '') {
                    text = '暂未开通'
                } else {
                    text = text.split(" ")[0]
                }
                that.setData({
                    nickname: res.data.data.nickname,
                    avatar: res.data.data.avatar,
                    integral: res.data.data.integral,
                    balance: res.data.data.balance,
                    commission: res.data.data.commission,
                    level: res.data.data.level_id,
                    user_id: res.data.data.user_id,
                    vip_express_time: text,
                    vip_amount: res.data.data.vip_amount,
                    hiddenLoading: true
                });
                wx.setStorageSync('is_vip', res.data.data.is_vip)
            }
        })
    },

    /**
     * 获取默认地址
     */
    getAddress: function () {
        console.log('收货地址了')
        var that = this;
        var options = this.data.options
        var paraArr = new Array();
        paraArr['user_id'] = that.data.userInfo.userID;
        paraArr['index'] = 1;
        var sign = app.signature(paraArr);
        wx.request({
            url: rootDocment + '/api_address',
            data: {
                user_id: paraArr['user_id'],
                index: paraArr['index'],
                sign: sign
            },
            method: 'GET',
            header: {},
            success: function (res) {
                console.log(res)
                if (res.data.length > 0) {
                    let address1 = res.data[0]['address1'] ? res.data[0]['address1'] : res.data[0]['address']
                    that.setData({
                        address_id: res.data[0]['id'],
                        link_name: res.data[0]['name'],
                        link_tel: res.data[0]['tel'],
                        link_addr: res.data[0]['province'] + " " + res.data[0]['city'] + " " + res.data[0]['county'] + " " + address1,
                        on_link_addr: res.data[0]['province']
                    });
                }
            },
            fail: function (err) {
                wx.hideLoading()

            }
        })

    },

    onClickShow() {
        this.setData({
            showKefu: true
        });
    },

    onClickHide() {
        this.setData({
            showKefu: false
        });
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        var that = this
        //用户授权登录
        app.login(function (userInfo) {
            that.setData({
                userInfo: userInfo
            });
            that.getUserInfo()
            that.getAddress()
        });
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
        this.getUserInfo()
        wx.stopPullDownRefresh();
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})